package com.mmlc.meimei.lichengkongjian.mine;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.network.filter.CustomerAddRequestFilter;
import com.mmlc.utils.PermissionUtils;
import com.mmlc.utils.ToastUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/28.
 */
public class ActivityAddCustomer extends InterActivity implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback {

    @InjectView(R.id.iv_back)
    ImageView iv_back;
    @InjectView(R.id.edt_name)
    EditText edtName;
    @InjectView(R.id.edt_phone)
    EditText edtPhone;
    @InjectView(R.id.iv_contacts)
    ImageButton iv_contacts;
    @InjectView(R.id.tv_save)
    TextView tvSave;

    @Override
    protected int initContentView() {
        return R.layout.activity_add_customer;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);

        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString("客户姓名");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        edtName.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

        ss = new SpannableString("手机号码");
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        edtPhone.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

    }


    @OnClick({R.id.iv_back, R.id.edt_name, R.id.edt_phone, R.id.iv_contacts, R.id.tv_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.edt_name:
                break;
            case R.id.edt_phone:
                break;
            case R.id.iv_contacts:
                //6.0动态权限READ_CONTACTS
                PermissionUtils.requestPermission(ActivityAddCustomer.this, PermissionUtils.CODE_READ_CONTACTS, mPermissionGrant);
                break;
            case R.id.tv_save:
                infoSub();
                break;
        }
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_READ_CONTACTS:
                    chooseContact();
                    break;
                default:
                    PermissionUtils.requestPermission(ActivityAddCustomer.this, PermissionUtils.CODE_READ_CONTACTS, mPermissionGrant);
                    break;
            }
        }
    };
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }


    private void infoSub() {
        if (TextUtils.isEmpty(edtName.getText())) {
            ToastUtils.showToast("请输入客户姓名");
            return;
        }
        if (TextUtils.isEmpty(edtPhone.getText())) {
            ToastUtils.showToast("请输入客户电话");
            return;
        }
        String replace = edtPhone.getText().toString().replace(" ", "");
        if (replace.length() != 11) {
            ToastUtils.showToast("请输入正确的手机号码");
            return;
        }
        submitCustomer();
    }

    private void submitCustomer() {
        CustomerAddRequestFilter filter = new CustomerAddRequestFilter((BaseParentActivity) activity);
        filter.requestBean.name = edtName.getText().toString();
        filter.requestBean.phone = edtPhone.getText().toString();
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast("添加成功");
                Intent intent = new Intent();
                intent.putExtra("type", 0);
                setResult(200, intent);
                finish();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });

    }

    private void chooseContact() {

//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setData(ContactsContract.Contacts.CONTENT_URI);
//        startActivityForResult(intent,0);
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.setData(Contacts.People.CONTENT_URI);
//        startActivity(intent);

//        Intent intent = new Intent(Intent.ACTION_PICK);
//        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
//        startActivityForResult(intent, 500);
//        Intent intent = new Intent(Intent.ACTION_PICK,
//                ContactsContract.Contacts.CONTENT_URI);
//        startActivityForResult(intent, 500);
//        printContacts();
            startActivityForResult(new Intent(this,ActivityContacts.class),100);
    }


    /*
    * 跳转联系人列表的回调函数
    * */

    private ReadContactMsg readContactMsg;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 500:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息

                //获取手机通讯录
                if (requestCode == 0) {
                    if (data != null) {
                        if (resultCode == AppCompatActivity.RESULT_OK) {
                            readContactMsg = new ReadContactMsg(this, data);
                            edtName.setText(readContactMsg.getName());
                            edtPhone.setText(readContactMsg.getPhone());
                        }
                    }
                    return;
                }
                super.onActivityResult(requestCode, resultCode, data);
            case 100:
                if (data == null) {
                    return;
                }
                edtName.setText(data.getStringExtra("name"));
                edtPhone.setText(data.getStringExtra("number"));
        }

    }

    class ReadContactMsg {
        private String name;
        private String phone;

        public ReadContactMsg(Context context, Intent data) {
            super();
            Uri contactData = data.getData();
            CursorLoader cursorLoader = new CursorLoader(context, contactData, null, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if (cursor.moveToFirst()) {
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                phone = "此联系人暂未存入号码";
                Cursor phones = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                        null,
                        null);
                if (phones.moveToFirst()) {
                    phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                phones.close();
            }
            cursor.close();
        }

        public String getName() {
            return name;
        }

        public String getPhone() {
            return phone;
        }
    }

    /*
  * 自定义显示Contacts提供的联系人的方法
  */
    public void printContacts() {
        //生成ContentResolver对象
        ContentResolver contentResolver = getContentResolver();

        // 获得所有的联系人
        /*Cursor cursor = contentResolver.query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
         */
        //这段代码和上面代码是等价的，使用两种方式获得联系人的Uri
        Cursor cursor = contentResolver.query(Uri.parse("content://com.android.contacts/contacts"), null, null, null, null);

        // 循环遍历
        if (cursor.moveToFirst()) {

            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            int displayNameColumn = cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            do {
                // 获得联系人的ID
                String contactId = cursor.getString(idColumn);
                // 获得联系人姓名
                String displayName = cursor.getString(displayNameColumn);

                //使用Toast技术显示获得的联系人信息
                Toast.makeText(this, "联系人姓名：" + displayName, Toast.LENGTH_LONG).show();


                // 查看联系人有多少个号码，如果没有号码，返回0
                int phoneCount = cursor
                        .getInt(cursor
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                if (phoneCount > 0) {
                    // 获得联系人的电话号码列表
                    Cursor phoneCursor = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                    + "=" + contactId, null, null);
                    if (phoneCursor.moveToFirst()) {
                        do {
                            //遍历所有的联系人下面所有的电话号码
                            String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            //使用Toast技术显示获得的号码
                            Toast.makeText(this, "联系人电话：" + phoneNumber, Toast.LENGTH_LONG).show();

                        } while (phoneCursor.moveToNext());
                    }
                }

            } while (cursor.moveToNext());
        }

    }
}
